package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.pojo.vo.DuYanAccountResponseParamVO;
import com.xbongbong.paas.pojo.vo.DuYanAccountVO;
import com.xbongbong.paas.pojo.vo.DuYanAgentVO;
import com.xbongbong.paas.pojo.vo.DuYanCallLogResponseParamVO;
import com.xbongbong.paas.pojo.vo.DuYanCallLogVO;
import com.xbongbong.paas.pojo.vo.DuYanOrganizationVO;
import com.xbongbong.paas.pojo.vo.DuYanTeamVO;
import com.xbongbong.paas.pojo.vo.DuYanTranscriptionResponseVO;
import com.xbongbong.paas.service.DuYanHttpService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.OkHttpUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.DuYanErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.PageConstant;
import com.xbongbong.saas.constant.callcenter.DuYanAcountApiConstant;
import com.xbongbong.saas.constant.callcenter.DuYanCallApiConstant;
import com.xbongbong.saas.constant.callcenter.DuYanConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author youli.chen
 * @version v1.0
 * @description: 度言http请求Service实现类
 * @date 2019/2/14 13:42
 * @since v1.0
 */
@Service("duYanHttpService")
public class DuYanHttpServiceImpl implements DuYanHttpService {

    private static final Logger LOG = LoggerFactory.getLogger(DuYanHttpServiceImpl.class);

    /**
     * 发起度言的Post的Https请求
     *
     * @param apiUrl 局部的请求地址
     * @param params 请求参数，在此封装apikey
     * @return JSONObject Response 的内容
     */
    private JSONObject doPost(String apiUrl, Map<String, Object> params) throws XbbException {
        apiUrl = DuYanConstant.BASE_URL + apiUrl;
        String result = OkHttpUtil.post(apiUrl, params);
        JSONObject responseBody = checkResponse(result);
        return responseBody;
    }

    /**
     * 发起度言的Get的Https请求
     *
     * @param apiUrl 局部的请求地址
     * @param params 请求参数，在此封装apikey
     * @return JSONObject Response 的内容
     */
    private JSONObject doGet(String apiUrl, Map<String, Object> params) throws XbbException {
        apiUrl = DuYanConstant.BASE_URL + apiUrl;
        String result = OkHttpUtil.get(apiUrl, params);
        JSONObject responseBody = checkResponse(result);
        return responseBody;


    }

    /**
     * 发起度言的Delete的Https请求
     *
     * @param apiUrl 局部的请求地址
     * @param params 请求参数，在此封装apikey
     * @return JSONObject Response 的内容
     */
    private JSONObject doDelete(String apiUrl, Map<String, Object> params) throws XbbException {
        apiUrl = DuYanConstant.BASE_URL + apiUrl;
        String result = OkHttpUtil.delete(apiUrl, params);
        JSONObject responseBody = checkResponse(result);
        return responseBody;
    }

    /**
     * 校验度言返回是否正确
     *
     * @param result 度言API返回 Response Body 字符串
     * @return JSONObject 解析成功的 Response Body JSON对象
     * @throws XbbException 封装的业务异常
     */
    private JSONObject checkResponse(String result) throws XbbException {
        JSONObject responseBody;
        try {
            responseBody = JSON.parseObject(result);
        } catch (JSONException jsonException) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302007);
        }
        if (isFailedRequest(responseBody)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, responseBody.getString(DuYanConstant.API_KEY_MESSAGE));
        }
        return responseBody;
    }

    /**
     * 校验度言API返回结果是否失败
     *
     * @param responseBody 返回数据转换的JSON对象
     * @return boolean 是否失败 true：失败 false：成功
     */
    private boolean isFailedRequest(JSONObject responseBody) {
        if (responseBody == null || !Objects.equals(responseBody.getInteger(DuYanConstant.API_KEY_STATUS),
                DuYanConstant.API_SUCCESS_STATUS)) {
            LOG.error("请求出错，返回数据：%s", JSON.toJSONString(responseBody));
            return true;
        }
        return false;
    }

    /**
     * 验证是否缺失度言方面缺失的apiKey
     *
     * @param apiKey
     * @throws XbbException
     */
    private boolean checkApiKey(String apiKey) throws XbbException {
        if (StringUtil.isEmpty(apiKey)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302008);
        }
        return true;
    }

    @Override
    public DuYanOrganizationVO registerOrganization(String name, String alias, String registerId)
            throws XbbException {
        Map<String, Object> params = new HashMap<>(4);
        params.put("apikey", DuYanConstant.API_KEY_PARTNER);
        params.put("name", name);
        params.put("alias", alias);
        params.put("register_id", registerId);
        params.put("wrap_up", "NEVER");
        JSONObject responseBody = doPost(DuYanConstant.API_ORGANIZATION_REGISTER, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.error("度言没有返回公司信息：%s", "注册企业API");
            return new DuYanOrganizationVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanOrganizationVO.class);
        }
    }

    @Override
    public String getOrgApiKey(Long orgId) throws XbbException {
        Map<String, Object> params = new HashMap<>(2);
        params.put("apikey", DuYanConstant.API_KEY_PARTNER);
        params.put("org_id", orgId);
        JSONObject responseBody = doGet(DuYanConstant.API_GET_ORGANIZATION_API_KEY, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.error("度言没有返回公司信息：%s", "获取企业APIKEY的API");
            return null;
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanOrganizationVO.class).getApiKey();
        }
    }

    /**
     * 获取企业的apikey
     *
     * @param apiKey 企业的apikey，可通过获取企业apikey接口获取
     * @return String apikey
     * @throws XbbException 度言返回的错误由业务处理
     * @auth youli.chen
     */
    @Override
    public DuYanOrganizationVO getCompanyMsg(String apiKey) throws XbbException {
        Map<String, Object> params = new HashMap<>(1);
        params.put("apikey", apiKey);
        JSONObject responseBody = doGet(DuYanConstant.API_ORGANIZATION_INFO, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.error("度言没有返回公司信息：%s", "获取企业信息");
            return new DuYanOrganizationVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanOrganizationVO.class);
        }
    }

    /**
     * 获取企业的apikey
     *
     * @param apiKey             企业的apikey，可通过获取企业apikey接口获取
     * @param orgId              企业的orgId，企业Id
     * @param orgPhoneProtection 号码可见总开关
     * @return String apikey
     * @throws XbbException 度言返回的错误由业务处理
     * @auth youli.chen
     */
    @Override
    public String updateCompanyPhone(String apiKey, Long orgId, String orgPhoneProtection) throws XbbException {
        Map<String, Object> params = new HashMap<>(3);
        params.put("apikey", apiKey);
        params.put("org_id", orgId);
        params.put("org_phone_protection", orgPhoneProtection);
        JSONObject responseBody = doPost(DuYanConstant.API_ORGANIZATION_SHOW_PHONE, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_STATUS))) {
            LOG.error("度言没有返回公司号码修改信息：%s", "公司号码修改信息");
            return null;
        } else {
            return responseBody.getString("status");
        }
    }

    @Override
    public List<DuYanTeamVO> getTeamList(String apiKey)
            throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(1);
        params.put("apikey", apiKey);
        JSONObject responseBody = doGet(DuYanConstant.API_TEAM_LIST, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("无有效团队列表");
            return new ArrayList<>();
        } else {
            return JSON.parseArray(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanTeamVO.class);
        }
    }

    @Override
    public DuYanTeamVO registerTeam(String apiKey, DuYanTeamVO team) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(5);
        params.put("apikey", apiKey);

        if (StringUtil.isEmpty(team.getName())) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302009);
        }
        params.put("name", team.getName());
        if (StringUtil.isEmpty(team.getPhoneVisibility())) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302010);
        }
        params.put("phone_visibility", team.getPhoneVisibility());
        if (team.getParentId() != null) {
            params.put("parent_id", team.getParentId());
        }
        if (team.getRemark() != null) {
            params.put("remark", team.getRemark());
        }

        JSONObject responseBody = doPost(DuYanConstant.API_TEAM_REGISTER, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("无有效团队");
            return new DuYanTeamVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanTeamVO.class);
        }
    }

    @Override
    public DuYanTeamVO updateTeam(String apiKey, DuYanTeamVO team) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(6);
        params.put("apikey", apiKey);

        if (team.getTeamId() == null) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302011);
        }
        if (StringUtil.isEmpty(team.getName())) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302012);
        }
        params.put("name", team.getName());
        if (StringUtil.isEmpty(team.getPhoneVisibility())) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302010);
        }
        params.put("phone_visibility", team.getPhoneVisibility());
        if (team.getParentId() != null) {
            params.put("parent_id", team.getParentId());
        }
        if (StringUtil.isNotEmpty(team.getRemark())) {
            params.put("remark", team.getRemark());
        }

        String url = String.format(DuYanConstant.API_TEAM_UPDATE, team.getTeamId());
        JSONObject responseBody = doPost(url, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("无有效团队");
            return null;
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanTeamVO.class);
        }
    }

    @Override
    public DuYanTeamVO getTeamDetail(String apiKey, Long teamId) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(1);
        params.put("apikey", apiKey);

        if (teamId == null) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302013);
        }

        String url = String.format(DuYanConstant.API_TEAM_DETAIL, teamId);
        JSONObject responseBody = doGet(url, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("无有效团队");
            return null;
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanTeamVO.class);
        }
    }

    @Override
    public List<DuYanAgentVO> getAgentList(String apiKey, String teamId)
            throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(2);
        params.put("apikey", apiKey);
        params.put("team_id", teamId);
        JSONObject responseBody = doGet(DuYanConstant.API_AGENT_LIST, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("无有效坐席列表");
            return new ArrayList<>();
        } else {
            return JSON.parseArray(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAgentVO.class);
        }
    }

    @Override
    public DuYanAccountResponseParamVO getAccountList(String apiKey, Integer pageNum, Integer pageSize, DuYanAccountVO account)
            throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(8);
        params.put("apikey", apiKey);
        if (pageNum == null || pageNum < 0) {
            pageNum = PageConstant.DEFAULT_INDEX_PAGE;
        }
        params.put("page_num", pageNum);
        if (pageSize == null || pageSize < 0 || pageSize > PageConstant.CALL_CENTER_DU_YAN_CALL_LOG_MAX_PAGE_SIZE) {
            pageSize = PageConstant.DEFAULT_PAGE_SIZE;
        }
        params.put("page_size", pageSize);
        if (account.getIsAdmin() != null) {
            params.put("is_admin", account.getIsAdmin());
        }
        if (account.getIsAgent() != null) {
            params.put("is_agent", account.getIsAgent());
        }
        if (account.getIsSupervisor() != null) {
            params.put("is_supervisor", account.getIsSupervisor());
        }
        if (StringUtil.isNotEmpty(account.getName())) {
            params.put("name", account.getName());
        }
        if (StringUtil.isNotEmpty(account.getMobile())) {
            params.put("mobile", account.getMobile());
        }
        JSONObject responseBody = doGet(DuYanAcountApiConstant.API_ACCOUNT_LIST, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("无有效员工列表");
            return new DuYanAccountResponseParamVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountResponseParamVO.class);
        }
    }

    @Override
    public DuYanAccountVO registerAccount(String apiKey, DuYanAccountVO account)
            throws XbbException{
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(4);
        params.put("apikey", apiKey);
        if (StringUtil.isEmpty(account.getName())) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302014);
        }
        params.put("name", account.getName());
        if (StringUtil.isNotEmpty(account.getTitle())) {
            params.put("title", account.getTitle());
        }
        if (StringUtil.isNotEmpty(account.getMobile())) {
            params.put("mobile", account.getMobile());
        }

        JSONObject responseBody = doPost(DuYanAcountApiConstant.API_ACCOUNT_REGISTER, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言没有返回员工信息");
            return new DuYanAccountVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
        }
    }

    @Override
    public Boolean deleteAccount(String apiKey, String accountId)
            throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(2);
        params.put("apikey", apiKey);
        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }

        String url = String.format(DuYanAcountApiConstant.API_ACCOUNT_DELETE, accountId);
        doDelete(url, params);

        return true;
    }

    @Override
    public DuYanAccountVO getAccount(String apiKey, String accountId)
            throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(2);
        params.put("apikey", apiKey);
        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        String url = String.format(DuYanAcountApiConstant.API_ACCOUNT_DETAIL, accountId);
        JSONObject responseBody = doGet(url, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("无有效员工");
            return new DuYanAccountVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
        }
    }

    @Override
    public DuYanAccountVO updateAccount(String apiKey, DuYanAccountVO account)
            throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(5);
        params.put("apikey", apiKey);
        if (account.getAccountId() == null) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        if (StringUtil.isEmpty(account.getName())) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302016);
        }
        params.put("name", account.getName());
        if (StringUtil.isNotEmpty(account.getTitle())) {
            params.put("title", account.getTitle());
        }
        if (StringUtil.isNotEmpty(account.getMobile())) {
            params.put("mobile", account.getMobile());
        }
        String url = String.format(DuYanAcountApiConstant.API_ACCOUNT_UPDATE, account.getAccountId().toString());
        JSONObject responseBody = doPost(url, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言没有返回员工信息");
            return new DuYanAccountVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
        }
    }

    @Override
    public DuYanAccountVO setAgent(String apiKey, String accountId, Long teamId, Boolean isSupervisor)
            throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(4);
        params.put("apikey", apiKey);
        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        if (teamId != null) {
            params.put("team_id", teamId);
        }
        if (isSupervisor != null) {
            params.put("is_supervisor", isSupervisor);
        }
        String url = String.format(DuYanAcountApiConstant.API_AGENT_SET, accountId);
        JSONObject responseBody = doPost(url, params);

        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言没有返回员工信息");
            return new DuYanAccountVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
        }
    }

    @Override
    public DuYanAccountVO deleteAgent(String apiKey, String accountId)
            throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(2);
        params.put("apikey", apiKey);
        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        String url = String.format(DuYanAcountApiConstant.API_AGENT_REMOVE, accountId);
        JSONObject responseBody = doDelete(url, params);

        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言没有返回员工信息");
            return new DuYanAccountVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
        }
    }

    @Override
    public DuYanAccountVO registerMobile(String apiKey, String accountId, String mobile)
            throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(3);
        params.put("apikey", apiKey);
        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        if (StringUtil.isNotEmpty(mobile)) {
            params.put("mobile", mobile);
        }
        String url = String.format(DuYanAcountApiConstant.API_ACCOUNT_MOBILE_REGISTER, accountId);
        JSONObject responseBody = doPost(url, params);

        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言没有返回员工信息");
            return new DuYanAccountVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
        }
    }

    @Override
    public DuYanAccountVO updateAccountTeam(String apiKey, String accountId, Long teamId, Boolean isSupervisor)
            throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(3);
        params.put("apikey", apiKey);
        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        if (teamId != null) {
            params.put("team_id", teamId);
        }
        if (isSupervisor != null) {
            params.put("is_supervisor", isSupervisor);
        }
        String url = String.format(DuYanAcountApiConstant.API_ACCOUNT_TEAM_SET, accountId);
        JSONObject responseBody = doPost(url, params);

        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言没有返回员工信息");
            return new DuYanAccountVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
        }
    }

    @Override
    public DuYanAccountVO deleteAccountTeam(String apiKey, String accountId, Long teamId)
            throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(3);
        params.put("apikey", apiKey);
        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        if (teamId != null) {
            params.put("team_id", teamId);
        }
        String url = String.format(DuYanAcountApiConstant.API_ACCOUNT_TEAM_REMOVE, accountId);
        JSONObject responseBody = doDelete(url, params);

        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言没有返回员工信息");
            return new DuYanAccountVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
        }
    }

    @Override
    public DuYanAccountVO setSupervisor(String apiKey, String accountId) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(2);
        params.put("apikey", apiKey);
        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        String url = String.format(DuYanAcountApiConstant.API_ACCOUNT_SUPERVISOR_SET, accountId);
        JSONObject responseBody = doPost(url, params);

        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言没有返回员工信息");
            return new DuYanAccountVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
        }
    }

    @Override
    public DuYanAccountVO cancelSupervisor(String apiKey, String accountId) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(2);
        params.put("apikey", apiKey);
        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        String url = String.format(DuYanAcountApiConstant.API_ACCOUNT_SUPERVISOR_REMOVE, accountId);
        JSONObject responseBody = doDelete(url, params);

        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言没有返回员工信息");
            return new DuYanAccountVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
        }
    }

    @Override
    public DuYanAccountVO setAdmin(String apiKey, String accountId) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(2);
        params.put("apikey", apiKey);
        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        String url = String.format(DuYanAcountApiConstant.API_ACCOUNT_ADMIN_SET, accountId);
        JSONObject responseBody = doPost(url, params);

        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言没有返回员工信息");
            return new DuYanAccountVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
        }
    }

    @Override
    public DuYanAccountVO cancelAdmin(String apiKey, String accountId) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(1);
        params.put("apikey", apiKey);
        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        String url = String.format(DuYanAcountApiConstant.API_ACCOUNT_ADMIN_REMOVE, accountId);
        JSONObject responseBody = doDelete(url, params);

        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言没有返回员工信息");
            return new DuYanAccountVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
        }
    }

    @Override
    public String accountLogin(String apiKey, String accountId) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(2);
        params.put("apikey", apiKey);
        params.put("account_id", accountId);
        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        JSONObject responseBody = doPost(DuYanConstant.API_LOGIN_CTI, params);

        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言没有返回token");
            return null;
        } else {
            DuYanAccountVO duYanAccountVO = JSON.parseObject(
                    responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
            if (duYanAccountVO == null) {
                return null;
            } else {
                if (StringUtil.isEmpty(duYanAccountVO.getToken())) {
                    return null;
                } else {
                    return duYanAccountVO.getToken();
                }
            }
        }
    }

    @Override
    public String adminLogin(String apiKey, String accountId) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(2);
        params.put("apikey", apiKey);

        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        params.put("account_id", accountId);

        JSONObject responseBody = doPost(DuYanConstant.API_ADMIN_LOGIN_CFG, params);

        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言没有返回token");
            return null;
        } else {
            DuYanAccountVO duYanAccountVO = JSON.parseObject(
                    responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanAccountVO.class);
            if (duYanAccountVO == null) {
                return null;
            } else {
                if (StringUtil.isEmpty(duYanAccountVO.getToken())) {
                    return null;
                } else {
                    return duYanAccountVO.getToken();
                }
            }
        }
    }

    @Override
    public boolean registerCallPhoneNum(String apiKey, String accountId, String target) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(3);
        params.put("apikey", apiKey);

        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        params.put("account_id", accountId);
        if (StringUtil.isEmpty(target)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302017);
        }
        params.put("target", target);
        JSONObject responseBody = doPost(DuYanCallApiConstant.API_CALL_SECRET_REGISTER, params);
        return responseBody.getInteger(DuYanConstant.API_KEY_STATUS) == 1;
    }

    @Override
    public String getRegisteredCallPhoneNum(String apiKey, String accountId) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(3);
        params.put("apikey", apiKey);

        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        params.put("account_id", accountId);
        JSONObject responseBody = doGet(DuYanCallApiConstant.API_CALL_SECRET_GET, params);

        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("获取度言注册的手机号失败");
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302003,
                    responseBody.getString(DuYanConstant.API_KEY_MESSAGE));
        } else {
            return responseBody.getJSONObject(DuYanConstant.API_KEY_DATA).getString("target");
        }
    }

    @Override
    public DuYanCallLogResponseParamVO getAgentMissedCallLogList(String apiKey, String accountId, Integer pageNum, Integer pageSize) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(4);
        params.put("apikey", apiKey);
        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302018);
        }
        params.put("account_id", accountId);
        if (pageNum == null || pageNum < 0) {
            pageNum = PageConstant.DEFAULT_INDEX_PAGE;
        }
        params.put("page_num", pageNum);
        if (pageSize == null || pageSize < 0 || pageSize > PageConstant.CALL_CENTER_DU_YAN_AGENT_MISSED_CALL_MAX_PAGE_SIZE) {
            pageSize = PageConstant.CALL_CENTER_DU_YAN_AGENT_MISSED_CALL_MAX_PAGE_SIZE;
        }
        params.put("page_size", pageSize);
        JSONObject responseBody = doGet(DuYanCallApiConstant.API_CALL_LOG_MISSED_LIST, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言查找坐席的未接电话列表出错");
            return new DuYanCallLogResponseParamVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanCallLogResponseParamVO.class);
        }
    }

    @Override
    public DuYanCallLogResponseParamVO getOrgMissedCallLogList(String apiKey, Integer pageNum, Integer pageSize, Long startTime, Long endTime, Long teamId) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(6);
        params.put("apikey", apiKey);
        if (pageNum == null || pageNum < 0) {
            pageNum = PageConstant.DEFAULT_INDEX_PAGE;
        }
        params.put("page_num", pageNum);
        if (pageSize == null || pageSize < 0 || pageSize > PageConstant.CALL_CENTER_DU_YAN_CALL_LOG_MAX_PAGE_SIZE) {
            pageSize = PageConstant.CALL_CENTER_DU_YAN_CALL_LOG_MAX_PAGE_SIZE;
        }
        params.put("page_size", pageSize);
        if (startTime == null) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302019);
        }
        if (endTime == null) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302020);
        }
        if (startTime >= endTime || endTime - startTime > DuYanConstant.CALL_LOG_MAX_INTERVAL) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302005);
        }
        params.put("start_time", startTime);
        params.put("end_time", endTime);
        if (teamId != null) {
            params.put("team_id", teamId);
        }
        JSONObject responseBody = doGet(DuYanCallApiConstant.API_CALL_LOG_MISSED_LIST, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.info("度言查找企业的未接电话列表出错");
            return new DuYanCallLogResponseParamVO();
        } else {
            DuYanCallLogResponseParamVO paramVO;
            try{
                paramVO = JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanCallLogResponseParamVO.class);
            }catch (Exception e){
                throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302021);
            }
            return paramVO;
        }
    }

    @Override
    public DuYanCallLogResponseParamVO getCallLogList(String apiKey, Integer pageNum, Integer pageSize, Long startTime,
                                                      Long endTime, Long teamId, Long memberId, String target,
                                                      Long codeId) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(8);
        params.put("apikey", apiKey);
        if (pageNum == null || pageNum < 0) {
            pageNum = PageConstant.DEFAULT_INDEX_PAGE;
        }
        params.put("page_num", pageNum);
        if (pageSize == null || pageSize < 0 || pageSize > PageConstant.CALL_CENTER_DU_YAN_CALL_LOG_MAX_PAGE_SIZE) {
            pageSize = PageConstant.DEFAULT_PAGE_SIZE;
        }
        params.put("page_size", pageSize);
        if (startTime == null) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302019);
        }
        if (endTime == null) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302020);
        }
        if (startTime >= endTime || endTime - startTime > DuYanConstant.CALL_LOG_MAX_INTERVAL) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302005);
        }
        params.put("start_time", startTime);
        params.put("end_time", endTime);
        if (teamId != null) {
            params.put("team_id", teamId);
        }
        if (memberId != null) {
            params.put("member_id", memberId);
        }
        if (StringUtil.isNotEmpty(target)) {
            params.put("target", target);
        }
        if (codeId != null) {
            params.put("code_id", codeId);
        }
        JSONObject responseBody = doGet(DuYanCallApiConstant.API_CALL_LOG_LIST, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.error("度言查找通话记录列表出错：%s", "获取通话记录API");
            return new DuYanCallLogResponseParamVO();
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanCallLogResponseParamVO.class);
        }
    }

    @Override
    public DuYanCallLogVO getCallLogDetail(String apiKey, String callUuid) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(2);
        params.put("apikey", apiKey);
        if (callUuid == null) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302022);
        }
        params.put("call_uuid", callUuid);
        JSONObject responseBody = doGet(DuYanCallApiConstant.API_CALL_LOG_DETAIL, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.error("度言查找通话记录详情出错 call_uuid：%s", callUuid);
            return null;
        } else {
            return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA), DuYanCallLogVO.class);
        }
    }

    @Override
    public String getRecordUrlStatic(String apiKey, String orgId, String callTime, String callUuid) throws XbbException {
        checkApiKey(apiKey);
        return String.format(DuYanCallApiConstant.URL_CALL_LOG_FILE, orgId, callTime, callUuid);
    }

    @Override
    public String getRecordUrlDynamic(String apiKey, String callUuid) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(2);
        params.put("apikey", apiKey);
        params.put("call_uuid", callUuid);
        return OkHttpUtil.get(DuYanConstant.BASE_URL + DuYanCallApiConstant.API_GET_CALL_RECORDING_URL, params);
    }

    @Override
    public String registerMobileCallPhoneNum(String apiKey, String accountId, String target) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(3);
        params.put("apikey", apiKey);

        if (StringUtil.isEmpty(accountId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302015);
        }
        params.put("account_id", accountId);
        if (StringUtil.isEmpty(target)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302017);
        }
        params.put("target", target);
        JSONObject responseBody = doPost(DuYanCallApiConstant.API_CALL_MOBILE_TARGET_REGISTER, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.error("度言注册手机端拨打号码失败：%s", target);
            return null;
        } else {
            try {
                return responseBody.getJSONObject(DuYanConstant.API_KEY_DATA).getString(DuYanConstant.API_KEY_DATA_MOBILE_TARGET);
            } catch (Exception e) {
                LOG.error("度言注册手机端拨打号码返回的不是指定格式：%s", JSON.toJSONString(responseBody));
                return null;
            }
        }
    }

    @Override
    public DuYanTranscriptionResponseVO postCallTranscription(String apiKey, String callUuid) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(16);
        params.put("apikey", apiKey);

        if (StringUtil.isEmpty(callUuid)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302022);
        }
        params.put("call_uuid", callUuid);
        JSONObject responseBody = doPost(DuYanCallApiConstant.API_CALL_TRANSCRIPTION_POST, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.error("度言提交语音翻译任务失败，公司ApiKey（%s），通话录音（%s）", apiKey, callUuid);
            return null;
        } else {
            try {
                return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA),
                        DuYanTranscriptionResponseVO.class);
            } catch (Exception e) {
                LOG.error("度言提交语音翻译任务转写返回数据错误：%s", JSON.toJSONString(responseBody));
                return null;
            }
        }
    }

    @Override
    public DuYanTranscriptionResponseVO getCallTranscription(String apiKey, String transcriptionId) throws XbbException {
        checkApiKey(apiKey);
        Map<String, Object> params = new HashMap<>(16);
        params.put("apikey", apiKey);

        if (StringUtil.isEmpty(transcriptionId)) {
            throw new XbbException(DuYanErrorCodeEnum.API_ERROR_302023);
        }
        params.put("transcription_id", transcriptionId);
        JSONObject responseBody = doGet(DuYanCallApiConstant.API_CALL_TRANSCRIPTION_POST, params);
        if (StringUtil.isEmpty(responseBody.getString(DuYanConstant.API_KEY_DATA))) {
            LOG.error("获取度言语音翻译失败，公司ApiKey（%s），通话录音翻译任务（%s）", apiKey, transcriptionId);
            return null;
        } else {
            try {
                return JSON.parseObject(responseBody.getString(DuYanConstant.API_KEY_DATA),
                        DuYanTranscriptionResponseVO.class);
            } catch (Exception e) {
                LOG.error("获取度言语音翻译转写返回数据错误：%s", JSON.toJSONString(responseBody));
                return null;
            }
        }
    }
}